package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exceptions.BusinessException;
import com.tanhua.utils.JwtUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 用户登录或注册
     */
    public Map loginVerification(String phone, String code) {
        //1、对验证码进行判断
        //1.1 从redis中获取，发送的验证码数据
        String redisCode = redisTemplate.opsForValue().get("CODE" + phone);
        //1.2 比较redis中的验证码和用户输入的验证码
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //1.3 如果验证码不一致，抛出异常
            ErrorResult result = ErrorResult.loginError();
            throw new BusinessException(result);
        }
        //1.4 如果验证码一致，将redis中的验证码数据删除
        redisTemplate.delete("CODE" + phone);
        //2、根据手机号码查询用户
        User user = userApi.findByMobile(phone);
        Boolean isNew = false; //老用户
        //3、用户不存在，保存用户信息
        String type = "0101"; //登录
        if(user == null) {  //注册
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            //保存对象，获取用户id
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;//新用户
            //将用户数据注册到环信
            huanXinTemplate.createUser("hx"+userId,"123456");//环信名（hx+userId），密码
            //更新用户表，更新环信账号和密码字段
            user.setHxUser("hx"+userId);
            user.setHxPassword("123456");
            userApi.update(user);
            type = "0102";
        }
//        //发送MQ消息
//        Map map1 = new HashMap();
//        map1.put("userId",user.getId().toString());
//        map1.put("type",type);
//        map1.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date())); //2020-09-25
//        String message = JSON.toJSONString(map1);
//        //路由key：操作的类型（用户登录/注册：用户操作，动态操作，视频操作）
//        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",message);

        mqMessageService.sendLogMessage(user.getId(),type,"log.user",null);

        //4、生成token
        Map map = new HashMap();
        map.put("id",user.getId());
        map.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(map);//存入token的数据

        //5、构造返回值Map
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }

    //完善用户信息
    public void saveUserInfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //上传用户头像
    public void head(Long userId, MultipartFile headPhoto) throws IOException {
        //1、上传文件到阿里云oss,获取URL地址
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());//文件名，文件输入流
        //2、根据图片的URL，判断图片是否具有头像
        boolean detect = aipFaceTemplate.detect(url);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            ErrorResult result = ErrorResult.faceError();
            throw new BusinessException(result);
        }
        //2.2 如果包含人脸，更新数据库 --使用mp更新，只需要new对象，设置id和需要更新的字段即可
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);
    }
}
